package cn.vic.config;

import cn.vic.util.FileUtil;
import com.alibaba.fastjson.JSON;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * 生成信息的历史记录
 */
public class HistoricalRecord {

    protected static String fileName = "historicalRecord.json";
    /**
     * 数组长度只保存20
     */
    protected int maxSize = 20;

    protected ArrayBlockingQueue<GenertorConfig> historicalRecords = new ArrayBlockingQueue<>(maxSize);


    /**
     * 加载配置
     */
    public void loadGenertorConfig() {
        File file = new File(getFilePath());
        if (!file.isFile()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String jsonContent = FileUtil.readFile(file);
        //读取json 可能会有顺序问题。
        List<GenertorConfig> hrs = JSON.parseArray(jsonContent, GenertorConfig.class);
        if (hrs != null && hrs.size() > 0) {
            for (GenertorConfig genertorConfig : hrs) {
                addRecord(genertorConfig);
            }
        }
    }

    /**
     * 添加
     *
     * @param config
     */
    public void addRecord(GenertorConfig config) {
        if (config != null) {
            if (historicalRecords.size() >= maxSize) {
                historicalRecords.poll();
            }
            historicalRecords.add(config);
        }
    }

    /**
     * 保存
     */
    public void save() {
        FileUtil.write(getFilePath(), JSON.toJSONString(historicalRecords));
    }

    /**
     * 获取list 集合
     *
     * @return
     */
    public List<GenertorConfig> getList() {
        List<GenertorConfig> genertorConfigs = new ArrayList<>();
        Iterator<GenertorConfig> iterator = historicalRecords.iterator();
        while (iterator.hasNext()) {
            genertorConfigs.add(iterator.next());
        }
        return genertorConfigs;
    }

    /**
     * 获取最新的导出配置
     *
     * @return
     */
    public GenertorConfig getNewestConfig() {
        List<GenertorConfig> genertorConfigs = getList();
        if (genertorConfigs != null && genertorConfigs.size() > 0) {
            return genertorConfigs.get(genertorConfigs.size() - 1);
        }
        return null;
    }


    /**
     * 获取json路径
     *
     * @return
     */
    protected String getFilePath() {
        //String path = getClass().getProtectionDomain().getCodeSource().getLocation().getFile() + File.separator + fileName;
        return System.getProperty("user.dir") + File.separator + fileName;
    }


}
